package com.example.casper.Experiment2024;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.casper.Experiment2024.data.Book;
import com.example.casper.Experiment2024.data.DataBank;

import java.util.ArrayList;
import java.util.List;

public class BookListFragment extends Fragment {



    public ArrayList<Book> books;
    private ActivityResultLauncher<Intent> launcherAdd;
    private ActivityResultLauncher<Intent> launcherUpdate;
    private RecyclerViewBookAdpater recyclerViewBookAdpater;



    public BookListFragment() {
        // Required empty public constructor
    }


    public static BookListFragment newInstance() {
        BookListFragment fragment = new BookListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        // Inflate the layout for this fragment
        View rootViewer = inflater.inflate(R.layout.fragment_book_list, container, false);

        RecyclerView mainRecyclerView = rootViewer.findViewById(R.id.recycler_view_the_book);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));

        DataBank databank=new DataBank(this.getContext());
        books = databank.readBooks();
        books = new ArrayList<>();
        if(books.isEmpty())
            books.add(new Book("软件项目管理案例教程（第3版）", R.drawable.book_2,2));

        recyclerViewBookAdpater = new RecyclerViewBookAdpater(books);
        mainRecyclerView.setAdapter(recyclerViewBookAdpater);

        registerForContextMenu(mainRecyclerView);
        return rootViewer;

    }


    private void showDeleteConfirmationDialog(int position) {
        new AlertDialog.Builder(this.getContext())
                .setTitle(R.string.are_you_sure)
                .setMessage(R.string.are_you_sure_you_want_to_delete)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        books.remove(position);
                        recyclerViewBookAdpater.notifyItemRemoved(position);
                        DataBank databank = new DataBank(BookListFragment.this.getContext());
                        databank.saveBooks(books);
                    }
                })
                .setNegativeButton(R.string.no, null)
                .show();
    }



    public boolean onContextItemSelected(MenuItem itemMenu ) {
        //item.getOrder()
        switch (itemMenu.getItemId()) {
            case 0:
                Intent intentAdd = new Intent(this.getContext(), BookDetailsActivity.class);
                intentAdd.putExtra("position", itemMenu.getOrder());
                launcherAdd.launch(intentAdd);
                break;
            case 1:
                Intent intentUpdate = new Intent(BookListFragment.this.getContext(), BookDetailsActivity.class);
                intentUpdate.putExtra("position", itemMenu.getOrder());
                Book bookObject= books.get(itemMenu.getOrder());
                intentUpdate.putExtra("item_name", bookObject.getTitle());
                intentUpdate.putExtra("item_price", bookObject.getPrice());
                launcherUpdate.launch(intentUpdate);
                break;
            case 2:
                int positionToDelete = itemMenu.getOrder();
                showDeleteConfirmationDialog(positionToDelete);
                break;

            default:
                return super.onContextItemSelected(itemMenu);
        }
        return true;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launcherAdd = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String bookName=data.getStringExtra("item_name");
                        double bookPrice= data.getDoubleExtra("item_price",0);
                        int position = data.getIntExtra("position",0)+1;
                        books.add(position,new Book(bookName, R.drawable.book_no_name,bookPrice));
                        recyclerViewBookAdpater.notifyItemInserted(position);
                        DataBank databank=new DataBank(BookListFragment.this.getContext());
                        databank.saveBooks(books);
                    }
                });
        launcherUpdate = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String bookName = data.getStringExtra("item_name");
                        double bookPrice = data.getDoubleExtra("item_price", 0);
                        int position = data.getIntExtra("position", 0);

                        // 获取现有的 Book 对象
                        Book existingBook = books.get(position);

                        // 更新 Book 对象的属性
                        existingBook.setTitle(bookName); // 假设有 setName 方法
                        existingBook.setPrice(bookPrice); // 假设有 setPrice 方法

                        // 通知 RecyclerView 更新
                        recyclerViewBookAdpater.notifyItemChanged(position);
                        DataBank databank=new DataBank(BookListFragment.this.getContext());
                        databank.saveBooks(books);
                    }
                });



    }


    private static class RecyclerViewBookAdpater extends RecyclerView.Adapter {
        private final List<Book> books;

        public RecyclerViewBookAdpater(List<Book> books) {
            this.books =books;
        }
        @NonNull
        @Override

        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.book, parent, false);
            return new MyViewHolder(view);
        }
        public List<Book> getListBooks(){
            return (ArrayList<Book>) books;
        }
        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyViewHolder myViewHolder= (MyViewHolder) holder;
            myViewHolder.getImageViewPicture().setImageResource(books.get(position).getCoverResourceId());
            myViewHolder.getTextViewName().setText(books.get(position).getTitle());

        }

        @Override
        public int getItemCount() {
            return books.size();
        }
        private static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            public ImageView getImageViewPicture() {
                return imageViewPicture;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            private final ImageView imageViewPicture;
            private final TextView textViewName;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                this.imageViewPicture= itemView.findViewById(R.id.image_view_book_cover);
                this.textViewName= itemView.findViewById(R.id.text_view_book_name);

                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作"); // 设置菜单标题

                // 添加三个上下文菜单项
                menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
                menu.add(0, 1, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
                menu.add(0, 2, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
            }
        }



    }


}
